<template>
  <div class="qa-page">
    <el-container>
      <el-header>
        <nav-bar></nav-bar>
      </el-header>
      <el-main>
        <div class="qa-container">
          <div class="qa-header">
            <h2>问答社区</h2>
            <el-button type="primary" @click="showAskDialog" v-if="isAuthenticated">
              <el-icon><Plus /></el-icon>
              提问
            </el-button>
          </div>

          <div class="qa-list">
            <el-card class="qa-list">
              <template #header>
                <div class="card-header">
                  <span>问答列表</span>
                  <el-button type="primary" @click="showAskDialog">提问</el-button>
                </div>
              </template>
              
              <div v-loading="loading" element-loading-text="加载中...">
                <div v-if="error" class="error-message">
                  <el-alert
                    :title="error"
                    type="error"
                    @close="error = ''"
                  />
                </div>

                <div v-else-if="questions.length === 0" class="empty-message">
                  <el-empty description="当前还没有问题">
                    <el-button type="primary" @click="showAskDialog">去提问</el-button>
                  </el-empty>
                </div>

                <template v-else>
                  <el-card v-for="qa in questions" :key="qa.id" class="qa-card">
                    <div class="qa-card-header">
                      <div class="user-info">
                        <el-avatar 
                          :size="32" 
                          :src="qa.author.avatar || getAvatarUrl(qa.author.username)"
                        ></el-avatar>
                        <div class="meta">
                          <span class="username">{{ qa.author.username }}</span>
                          <span class="time">{{ formatDate(qa.createdAt) }}</span>
                        </div>
                      </div>
                      <div class="stats">
                        <el-tag size="small" type="info">{{ qa.answers.length }} 回答</el-tag>
                        <el-tag 
                          size="small" 
                          :type="qa.status === 'open' ? 'success' : 'info'"
                          class="status-tag"
                        >
                          {{ qa.status === 'open' ? '进行中' : '已解决' }}
                        </el-tag>
                      </div>
                    </div>

                    <h3 class="qa-title" @click="viewQuestion(qa.id)">{{ qa.title }}</h3>
                    <p class="qa-content">{{ qa.content }}</p>

                    <div class="qa-footer">
                      <div class="actions">
                        <el-button text type="primary" @click="viewQuestion(qa.id)">
                          查看详情
                        </el-button>
                      </div>
                      <div class="tags">
                        <el-tag
                          v-for="tag in qa.tags"
                          :key="tag"
                          size="small"
                          effect="plain"
                          class="tag"
                        >
                          {{ tag }}
                        </el-tag>
                      </div>
                    </div>
                  </el-card>
                </template>

                <el-pagination
                  v-if="total > 0"
                  v-model:current-page="currentPage"
                  v-model:page-size="pageSize"
                  :total="total"
                  :page-sizes="[10, 20, 30, 50]"
                  layout="total, sizes, prev, pager, next"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-card>
          </div>
        </div>
      </el-main>
      <el-footer>
        <footer-component></footer-component>
      </el-footer>
    </el-container>

    <!-- 提问对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="发起提问"
      width="50%"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="questionFormRef"
        :model="formData"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="问题标题" prop="question">
          <el-input
            v-model="formData.question"
            placeholder="请输入问题标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="问题描述" prop="content">
          <el-input
            v-model="formData.content"
            type="textarea"
            :rows="6"
            placeholder="请详细描述你的问题"
            maxlength="1000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="标签">
          <el-select
            v-model="formData.tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请选择或输入标签"
          >
            <el-option
              v-for="tag in commonTags"
              :key="tag"
              :label="tag"
              :value="tag"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            发布问题
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import NavBar from '../components/NavBar.vue'
import FooterComponent from '../components/FooterComponent.vue'
import { getQuestions, createQuestion } from '../api/qa'

export default {
  name: 'QA',
  components: {
    NavBar,
    FooterComponent,
    Plus
  },
  setup() {
    const store = useStore()
    const router = useRouter()
    const questionFormRef = ref(null)
    const dialogVisible = ref(false)
    const submitting = ref(false)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const total = ref(0)
    const questions = ref([])
    const loading = ref(false)
    const error = ref('')

    const formData = reactive({
      question: '',
      content: '',
      tags: []
    })

    const isAuthenticated = computed(() => store.getters.isAuthenticated)

    const commonTags = [
      'Vue.js',
      'React',
      'JavaScript',
      'Node.js',
      'Python',
      '前端开发',
      '后端开发',
      '数据库',
      '算法',
      '面试'
    ]

    const rules = {
      question: [
        { required: true, message: '请输入问题标题', trigger: 'blur' },
        { min: 5, max: 100, message: '标题长度在 5 到 100 个字符', trigger: 'blur' }
      ],
      content: [
        { required: true, message: '请输入问题描述', trigger: 'blur' },
        { min: 10, message: '描述不能少于10个字符', trigger: 'blur' }
      ]
    }

    const fetchQuestions = async () => {
      loading.value = true
      error.value = ''
      
      try {
        const params = {
          page: currentPage.value,
          pageSize: pageSize.value,
          user_id: store.state.user?.id
        }
        
        console.log('获取问题列表参数：', params)
        const res = await getQuestions(params)
        const {qaList, totalPages, currentPage: serverCurrentPage} = res
        console.log('获取问题列表响应：', qaList)
        
        if (!qaList) {
          throw new Error('获取数据失败，请检查服务器连接')
        }

        // 标准化数据格式
        const normalizedQuestions = qaList.map(item => {
          // 处理两种可能的数据结构
          const q = item.question || item
          return {
            id: item._id,
            title: q.title,
            content: q.content,
            author: q.author || {
              username: '未知用户',
              avatar: ''
            },
            createdAt: q.createdAt,
            answers: item.answers || [],
            tags: q.tags || [],
            status: item.status
          }
        })

        questions.value = normalizedQuestions
        // 计算总数据量：对于非最后一页，使用pageSize；最后一页使用实际数据长度
        total.value = serverCurrentPage < totalPages 
          ? (totalPages - 1) * pageSize.value + pageSize.value
          : (totalPages - 1) * pageSize.value + qaList.length
        console.log('处理后的问题列表：', questions.value)

      } catch (err) {
        console.error('获取问题列表错误:', err)
        error.value = err.message || '获取问题列表失败，请检查网络连接'
        questions.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      fetchQuestions()
    })

    watch([currentPage, pageSize], () => {
      fetchQuestions()
    })

    const formatDate = (date) => {
      if (!date) return '未知时间'
      return new Date(date).toLocaleDateString('zh-CN', {
        year: 'numeric',
        month: 'long',
        day: 'numeric',
        hour: '2-digit',
        minute: '2-digit'
      })
    }

    const getAvatarUrl = (username) => {
      return `https://ui-avatars.com/api/?name=${encodeURIComponent(username)}&background=random`
    }

    const showAskDialog = () => {
      dialogVisible.value = true
    }

    const handleDialogClose = () => {
      formData.question = ''
      formData.content = ''
      formData.tags = []
      questionFormRef.value?.resetFields()
      dialogVisible.value = false
    }

    const handleSubmit = async () => {
      if (!questionFormRef.value) return

      try {
        await questionFormRef.value.validate()
        submitting.value = true

        // 确保数据格式正确
        const questionData = {
          title: formData.question.trim(),
          content: formData.content.trim(),
          tags: formData.tags.map(tag => tag.trim()).filter(tag => tag)
        }

        // 添加请求前的数据验证
        if (!questionData.title || !questionData.content) {
          throw new Error('标题和内容不能为空')
        }

        console.log('提交的问题数据：', questionData)
        await createQuestion(questionData)
        ElMessage.success('问题发布成功')
        handleDialogClose()
        await fetchQuestions()
      } catch (error) {
        console.error('发布问题错误：', error)
        ElMessage.error(error.response?.data?.message || error.message || '发布失败，请重试')
      } finally {
        submitting.value = false
      }
    }

    const viewQuestion = (id) => {
      router.push(`/qa/${id}`)
    }

    const handleSizeChange = (val) => {
      pageSize.value = val
      fetchQuestions()
    }

    const handleCurrentChange = (val) => {
      currentPage.value = val
      fetchQuestions()
    }

    return {
      questions,
      currentPage,
      pageSize,
      total,
      isAuthenticated,
      dialogVisible,
      questionFormRef,
      formData,
      rules,
      submitting,
      commonTags,
      formatDate,
      getAvatarUrl,
      showAskDialog,
      handleDialogClose,
      handleSubmit,
      viewQuestion,
      handleSizeChange,
      handleCurrentChange,
      loading,
      error
    }
  }
}
</script>

<style scoped>
.qa-page {
  min-height: 100vh;
}

.el-header {
  padding: 0;
  height: auto;
}

.el-main {
  max-width: 1000px;
  margin: 0 auto;
  padding: 20px;
}

.qa-container {
  background: #fff;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.qa-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.qa-header h2 {
  margin: 0;
  color: #303133;
}

.qa-card {
  margin-bottom: 20px;
}

.qa-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.meta {
  display: flex;
  flex-direction: column;
}

.username {
  font-weight: 500;
  color: #303133;
}

.time {
  font-size: 0.9em;
  color: #909399;
}

.qa-title {
  margin: 0 0 10px;
  font-size: 1.2em;
  color: #303133;
  cursor: pointer;
}

.qa-title:hover {
  color: #409EFF;
}

.qa-content {
  color: #606266;
  margin: 0 0 15px;
  line-height: 1.6;
}

.qa-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.tags {
  display: flex;
  gap: 8px;
}

.tag {
  cursor: pointer;
}

.pagination {
  margin-top: 30px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

:deep(.el-dialog__body) {
  padding-top: 10px;
}

:deep(.el-select) {
  width: 100%;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.error-message {
  margin: 20px 0;
}

.empty-message {
  text-align: center;
  color: #909399;
  padding: 30px 0;
}
</style> 